console.log("inject content.js in weibo");
//在多微博列表的评论展开中，添加一个搜索按钮跳转到微博详情
function getLoad_more_a(div_mid){
    var $feed = $(div_mid).find("[node-type='feed_list_repeat']")[0];
    var we_empty = $($feed).children(".WB_empty");
    var timeoutInstace = $(div_mid).data("timeout");
    if(we_empty.length!=0){
        window.clearTimeout(timeoutInstace);
        timeoutInstace = window.setTimeout(getLoad_more_a,1000,div_mid);
    }else{
        var commentList = $($feed).find("div[node-type='commentList']");
        var load_more_a = $($feed).find(".repeat_list")
                                .children(".list_box")
                                .children(".list_ul")
                                .children("a");
        //获取微博详情的跳转url
        var url = $(load_more_a).attr("href");
        console.log("open url "+url);
        var btn_div = $(commentList).find("div.p_opt");
        var html_btn = '<div class="btn W_fr" style="margin-left:10px;">'+
                        '<a target="_blank"  href="'+url+'"'+
                        'class="W_btn_a W_btn_a_enable W_btn_a6 btn_search">搜索评论</a></div>';
        $(btn_div).prepend(html_btn);
        //$(load_more_a)[0].click();
        // window.clearTimeout(timeoutInstace);
        // window.open(url,"");
    }
}
$(document).on('click',"a[action-type='fl_comment'],a[action-type='feed_list_comment']",function(){
    var parent = $(this).parents("div[mid]")[0];
    var feed_list_repeat_css = $(parent).find("[node-type=\"feed_list_repeat\"]").css("display");
    if(feed_list_repeat_css!="none"){
        var mid = $(parent).attr("mid");
        console.log("find the mid:"+mid);
        var div_mid = $("div[mid=\'"+mid+"\']")[0];
        var timeoutInstace = window.setTimeout(getLoad_more_a,1000,div_mid);
        $(div_mid).data("timeout",timeoutInstace);
    }else{
        console.log("comment list is close");
        var timeoutInstace = $(div_mid).data("timeout");
        window.clearTimeout(timeoutInstace);
    }

});
//微博搜索功能实现
var $repeat_list ;      //jquery object selector is div.WB_feed_repeat div.repeat_list
var $cardpage;          //jquery object page numbers outter div
var page_numbers;
var page_current = 1;
var page_old = 0;
var $page ;
var comment_id;

var fixed_tools = '<div id="searchTools" style=" position: fixed; top: 200px; left: 30px; "> <div style="margin-bottom:10px;"> <input id="own_text" placeholder="搜索评论" type="text" class="W_input" style="overflow: hidden; height: 23px;"> </div> <div> <a id="own_pre" href="javascript:void(0);" class="W_btn_a W_btn_a_enable"> <em node-type="btnText">上一个</em></a> <a id="own_next" href="javascript:void(0);" class="W_btn_a W_btn_a_enable" style="margin-left:5px;"> <em node-type="btnText">下一个</em></a></div> <div style=" margin-top: 10px; "><a id="own_cancel" href="javascript:void(0);" class="W_btn_a W_btn_a_enable" > <em node-type="btnText">取消</em></a> <a id="own_close" href="javascript:void(0);" class="W_btn_a W_btn_a_enable" style="margin-left:5px;"> <em node-type="btnText">关闭</em></a></div> </div>';
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(sender.tab ?
                    "from a content script:" + sender.tab.url :
                    "from the extension");
        if (request.search_C == "true"){
            sendResponse({receive: "comment search now"});
            //防止重复点击添加多个div
            if($("#searchTools").length==0){
                $("body").append(fixed_tools);
                $repeat_list = $(".WB_feed_repeat").find(".repeat_list")[0];
                updateNode();
                $("#own_text").focus();
            }
        }
});
//自动跳转变量持有
var searchTime ;
//按钮点击事件响应
$(document).on("click","#own_pre",function(e){
    e.preventDefault();
    searchBtntips(true);
    var s = $("#own_text").val();
    if(s!=undefined&&s!=""){
        if(searchTime!=undefined||searchTime!=null)
            window.clearTimeout(searchTime);
        searchUntil(s,false);
    }
});
$(document).on("click","#own_next",function(e){
    e.preventDefault();
    searchBtntips(true);
    var s = $("#own_text").val();
    if(s!=undefined&&s!=""){
        if(searchTime!=undefined||searchTime!=null)
            window.clearTimeout(searchTime);
        searchUntil(s,true);
    }
});
$(document).on("click","#own_cancel",function(e){
    e.preventDefault();
    searchBtntips(false);
    $($repeat_list).find("div.list_box").removeAttr("async-type");
    if(searchTime!=undefined||searchTime!=null){
        window.clearTimeout(searchTime);
        console.log("cancel search ");
    }
});
$(document).on("click","#own_close",function(e){
    e.preventDefault();
    $("body>#searchTools").remove();
    if(searchTime!=undefined||searchTime!=null){
        window.clearTimeout(searchTime);
        console.log("cancel search ");
    }
});
//信息提示
function searchBtntips(flag){
    if(flag){
        $("#own_pre").removeClass("W_btn_a_enable")
                    .addClass("W_btn_a_disable")
                    .text("正在");
        $("#own_next").removeClass("W_btn_a_enable")
                    .addClass("W_btn_a_disable")
                    .text("搜索");
        $("#own_text").attr("disabled","true");
    }else{
        $("#own_pre").addClass("W_btn_a_enable")
                    .removeClass("W_btn_a_disable")
                    .text("上一个");
        $("#own_next").addClass("W_btn_a_enable")
                    .removeClass("W_btn_a_disable")
                    .text("下一个");
        $("#own_text").removeAttr("disabled","false");
    }
}
//评论异步加载后，更新相关变量
function updateNode(){
    //异步加载评论列表后，重新获取新的分页 div
    $cardpage = $($repeat_list).find(".W_pages");
    //获取分页 a 标签的数组
    var pageArray = $($cardpage).children("a");
    //获取当前微博的评论分页数
    page_numbers = $(pageArray[pageArray.length-2]).text().trim();
    //获取当前所在的分页页码
    var $pageA = $($cardpage).children(".S_bg2")[0];
    page_current = $($pageA).text().trim();
    //将字符串转换为数字整型
    page_current = parseInt(page_current);
    page_numbers = parseInt(page_numbers);
    //获取当前微博的翻页标识代码
    if($page==undefined||$page==""){
        $page = $($pageA).attr("action-data");
    //debug :Uncaught TypeError: Cannot read property 'substring' of undefined
        $page = $page.substring(0,$page.lastIndexOf("=")+1);
    }
    console.log("page a link "+$page);
    console.log("page current numb: "+page_current+" ,Now "+page_numbers+" pages");
}
//网络错误，加载不了评论，恢复重新加载
var W_pages_begin = '<div class="WB_cardpage S_line1" action-type="commentFilter"> <div class="W_pages"> <a action-data="id=3996522784285425&amp;page=';
var W_pages_end = '" class="page S_txt1" href="javascript:void(0);" action-type="feed_list_page">重新加载</a></div> </div>'
//触发评论分页点击事件 next 为 true向下翻页，false向上翻页
function turnOn(next){
    updateNode();
    var asyncType = $($repeat_list).find("div.list_box").attr("async-type");
    if(asyncType!=undefined&&asyncType=="01"){
        console.log("waiting the page async loading, page_current is "+page_current);
        return true;
    }else if(asyncType=="11"){
        if(page_current == page_old){
            if(next){
                page_current=page_current+1;
            }else{
                page_current=page_current-1;
            }
        }
        var p = 0;
        if(next){
            p=page_current+1;
        }else{
            p=page_current-1;
        }
        if(p<=page_numbers && p>=1){
            //获取目标分页链接
            var page = $($cardpage).children("a[action-data='"+$page+p+"']");
            console.log("going to next page number is "+p);
            console.log("trigger "+"a[action-data='"+$page+p+"']");
            //触发事件
            if(page.length!=0){
                $(page)[0].click();
            } else {
                //$repeat_list = $(".WB_feed_repeat").find(".repeat_list")[0];
                $page = "";
                return true;
            }
            $($repeat_list).find("div.list_box").attr("async-type","01");
            page_old = page_current;
            return true;
        }else if(isNaN(page_current)){
            var list_ul = $($repeat_list).find("div.list_box").children("div.list_ul");
            page_old++;
            $(list_ul).remove("div.WB_cardpage").append(W_pages_begin+page_old+W_pages_end);
            var page = $(list_ul).find("a[action-type='feed_list_page']");
            $(page)[0].click();
            $($repeat_list).find("div.list_box").attr("async-type","01");
            return true;
        }
    }else if(asyncType==undefined&& $cardpage.length==0){
        var list_ul = $($repeat_list).find("div.list_box").children("div.list_ul");
        $(list_ul).remove("div.WB_cardpage").append(W_pages_begin+page_old+W_pages_end);
        var page = $(list_ul).find("a[action-data]");
        $(page)[0].click();
        $($repeat_list).find("div.list_box").attr("async-type","01");
        return true;
    }else if(asyncType==undefined&& $cardpage.length!=0){
        var page = $($cardpage).children(".S_bg2");
        $(page)[0].click();
        $($repeat_list).find("div.list_box").attr("async-type","01");
        return true;
    }else{
        return false;
    }
}
//搜索速度调整，过快会跳过已经搜索到的评论
var wait_time = 800;
var loop_num = 0;
//评论搜索入口
function searchUntil(s,next){
    if(!findComment(s,next)){
        console.log("current page not found . pagenumber is "+page_current);
        if(turnOn(next)){
            searchTime = window.setTimeout(searchUntil,wait_time,s,next);
            return ;
        }
    }
    console.log("no more page to find , clear timeout !");
    window.clearTimeout(searchTime);
    searchBtntips(false);
    return ;
}
//递归搜索方法
function findComment(s,next){
    var comList = $($repeat_list).find("div[comment_id]").toArray();
    var asyncType = $($repeat_list).find("div.list_box").attr("async-type");
    if(comList.length==0||asyncType=="11"||asyncType=="01"){
        if(loop_num<10){
            loop_num++;
        }else{
            loop_num = 0;
            page_current++;
        }
        return false;
    }else if(asyncType==undefined){
        if(comment_id!=undefined&&comment_id!=""){
            var $com = $($repeat_list).find("[comment_id='"+comment_id+"']")[0];
            if($com!=undefined){
                var list ;
                if(!next){
                    list = $($com).prevAll("[comment_id]");
                }else{
                    list = $($com).nextAll("[comment_id]");
                }
                return commentEach(list,next,s);
            }// end if
            else{
                comment_id = "";
                return findComment(s,next);
            }
        }else{
            return commentEach(comList,next,s);
        }
    }
}// end for findComment function
// make the comment background color #f5dacd
function makeColor(divs){
    $(divs).css({"background-color":"#f5dacd"});
    comment_id = $(divs).attr("comment_id");
    console.log("find the one comment "+comment_id);
    searchBtntips(false);
    scrollToComment(divs);
    window.clearTimeout(searchTime);
}
//将页面滚动到找到的评论所在位置
function scrollToComment(divC){
    $("html, body").animate(
        { scrollTop: $(divC).offset().top-100 + "px"},
        {
            duration: 700,
            easing: "swing"
        }
    );
}
// foreach commnet list
function commentEach(comList,next,s){
    if(!next){
        for(var i=comList.length;i>=0;i--){
            var com_text=$(comList[i]).text();
            com_text = replaceSpace(com_text);
            if(com_text.indexOf(s)!=-1){
                makeColor(comList[i]);
                $($repeat_list).find("div.list_box").removeAttr("async-type");
                return true;
            }else {
                continue;
            }
        }
    }else{
        for(var i=0;i<comList.length;i++){
            var com_text=$(comList[i]).text();
            com_text = replaceSpace(com_text);
            if(com_text.indexOf(s)!=-1){
                makeColor(comList[i]);
                $($repeat_list).find("div.list_box").removeAttr("async-type");
                return true;
            }else {
                continue;
            }
        }
    }
    $($repeat_list).find("div.list_box").attr("async-type","11");
    return false;
}
//replace redundant space
function replaceSpace(text){
    var reg = /\s+/m;
    //console.log("matach text length is "+text.length);
    // var t = text.trim();
    // t = t.split(reg).join(" ");
    var t = text.split(reg).join(" ");
    //console.log("trim space text length "+t.length);
    return t;
}
